package com.example.demo.util.ssl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SimpleKeyStoreTrustManager implements X509TrustManager {

    private Logger logger = LoggerFactory.getLogger(SimpleKeyStoreTrustManager.class);

    private X509TrustManager actualTrustManager;

    public SimpleKeyStoreTrustManager(KeyStore ks) throws NoSuchAlgorithmException, KeyStoreException {
        String algorithm = TrustManagerFactory.getDefaultAlgorithm();
        logger.debug("build trustmanagerfactory use :" + algorithm);
        TrustManagerFactory factory = TrustManagerFactory
                .getInstance(algorithm);
        factory.init(ks);
        TrustManager[] trustManagers = factory.getTrustManagers();
        if (trustManagers.length <= 0) {
            throw new NoSuchAlgorithmException("trustManager not found!");
        }
        actualTrustManager = (X509TrustManager) trustManagers[0];
    }

    public SimpleKeyStoreTrustManager(X509Certificate[] chain) {
        // TODO
        throw new UnsupportedOperationException("not support yet");
    }

    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        actualTrustManager.checkClientTrusted(arg0, arg1);
    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        actualTrustManager.checkServerTrusted(arg0, arg1);
    }

    public X509Certificate[] getAcceptedIssuers() {
        return actualTrustManager.getAcceptedIssuers();
    }

}
